import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import DefaultLayout from '../components/Layout/DefaultLayout.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    component: DefaultLayout,
    children: [
      {
        path: 'dashboard-list',
        name: 'DashboardList',
        component: () => import('../views/DashboardList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'dashboard/:id',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'model',
        name: 'ModelManage',
        component: () => import('../views/Model.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: 'database',
        name: 'DatabaseManage',
        component: () => import('../views/Database.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: 'prompt',
        name: 'PromptManage',
        component: () => import('../views/Prompt.vue'),
        meta: {
          requiresAuth: true
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  // 检查token是否存在
  const token = localStorage.getItem('token')
  
  if (to.matched.some(record => record.meta.requiresAuth) && !token) {
    // 如果需要登录但未登录，重定向到登录页
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router 